package net.kazed.nextaction.database.serialize;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;

public class ContextHandler extends AbstractElementHandler implements ElementHandlerContext<ContextDto> {

        private ContextDto currentContext;
        private List<ContextDto> contexts = new ArrayList<ContextDto>();

        public ContextHandler() {
            super();
            addElementHandler("id", new ContextIdHandler(this));
            addElementHandler("parentId", new ContextParentIdHandler(this));
            addElementHandler("name", new ContextNameHandler(this));
        }

        public ContextHandler(Map<String, ElementHandler> elementHandlers) {
            super(elementHandlers);
            // TODO Auto-generated constructor stub
        }

        public ContextDto getCurrentContext() {
            return currentContext;
        }

        public List<ContextDto> getContexts() {
            return contexts;
        }

        @Override
        public void startElement(String name, Attributes attributes,
                ParserState state) {
            currentContext = new ContextDto();
        }

        @Override
        public void endElement(String name, ParserState state) {
            contexts.add(currentContext);
            currentContext = null;
        }
        
        @Override
        public ContextDto getContextData() {
            return currentContext;
        }
        
        private static class ContextIdHandler extends AbstractElementHandlerWithContext<ContextDto> {
            public ContextIdHandler(ElementHandlerContext<ContextDto> handlerContext) {
                super(handlerContext);
            }
            @Override
            public void characters(String text, ParserState state) {
                getContextData().setId(Long.valueOf(text));
            }
        }
        
        private static class ContextNameHandler extends AbstractElementHandlerWithContext<ContextDto> {
            public ContextNameHandler(ElementHandlerContext<ContextDto> handlerContext) {
                super(handlerContext);
            }
            @Override
            public void characters(String text, ParserState state) {
                getContextData().setName(text);
            }
            @Override
            public boolean isValueEncoded() {
                return true;
            }
        }
        
        private static class ContextParentIdHandler extends AbstractElementHandlerWithContext<ContextDto> {
            public ContextParentIdHandler(ElementHandlerContext<ContextDto> handlerContext) {
                super(handlerContext);
            }
            @Override
            public void characters(String text, ParserState state) {
                getContextData().setParentId(Long.valueOf(text));
            }
        }

}
